<?php


namespace App\Models;

use App\Models\Traits\SerializeDate;
use App\Models\Traits\TimeScope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * @method static \Illuminate\Database\Eloquent\Builder allowedIncludesWhere(string|array $allowed_includes);
 */
class BaseModel extends Model
{
    use TimeScope;
    use SerializeDate;

    // use ExtenHasRelationships;//测试
    protected $guarded = ['created_at', 'updated_at', 'deleted_at'];
    protected $defaultCasts = ['enable_status' => 'bool', 'param' => 'json', 'request' => 'json'];
    protected $hidden = ['password'];

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        parent::mergeCasts($this->defaultCasts);

        // Illuminate\Database\Query\Builder 扩展方法【迁移至EloquentBuilderMacroServiceProvider服务提供者中】
    }

    public static function new()
    {
        return new static();
    }

    public static function getTableName()
    {
        return with(new static)->getTable();
    }

    public static function getMorphClassName()
    {
        return with(new static)->getMorphClass();
    }

    protected static function boot()
    {
        parent::boot();
        static::saving(function (self $obj) {
            if (!empty($obj->version)) {
                $obj->version = DB::raw('version + 1');
            }
        });
    }

    public function ican()
    {
        $dirty = $this->getDirty();
        $updatedAt = $this->getUpdatedAtColumn();
        $query = self::query()->where($this->getKeyName(), $this->getKey())->where($updatedAt, $this->{$updatedAt});

        foreach ($dirty as $key => $value) {
            $query = $query->where($key, $this->getRawOriginal($key));
        }
        return $query->update($dirty);
    }
}
